package cn.school.demo.ui.edit

import android.annotation.SuppressLint
import android.app.DatePickerDialog
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import cn.school.demo.MyApplication
import cn.school.demo.R
import cn.school.demo.databinding.EditInfoFragmentBinding
import com.blankj.utilcode.util.LogUtils
import com.lzy.imagepicker.ui.ImageGridActivity
import com.mylhyl.circledialog.CircleDialog
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.runtime.Permission
import java.time.LocalDate

class EditInfoFragment : Fragment() {

    private lateinit var viewModel: EditInfoViewModel
    private lateinit var binding: EditInfoFragmentBinding

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        MyApplication.systemBarSetting(MyApplication.DARK, requireActivity())
        viewModel = ViewModelProvider(this).get(EditInfoViewModel::class.java)
        binding = DataBindingUtil.inflate(inflater, R.layout.edit_info_fragment, container, false)
        binding.vm = viewModel
        binding.vvv = this
        binding.my = MyApplication
        binding.lifecycleOwner = viewLifecycleOwner
        MyApplication.setCircleGlideByUrlString(
            requireContext(),
            MyApplication.user!!.headPortrait,
            binding.editFragmentAvatarImage
        )
        return binding.root
    }

    fun editSex() {
        CircleDialog.Builder()
            .setItems(listOf("女", "男")) { _, _, position, _ ->
                LogUtils.d(position)
                viewModel.setSex(position)
                true
            }.show(parentFragmentManager)
    }

    fun editArea() {
        CircleDialog.Builder().setInputText(viewModel.area.value ?: "", "请输入地址")
            .setInputHeight(Gravity.CENTER)
            .setInputCounter(30 * 3) { maxLen: Int, currentLen: Int ->
                "${(maxLen - currentLen) / 3} /${maxLen / 3}"
            }
            .setInputCounterColor(Color.BLACK).setInputShowKeyboard(true)
            .setPositiveInput("确定") { text, _ ->
                LogUtils.e(text)
                viewModel.setArea(text)
                true
            }
            .setNegative("取消", null)
            .show(parentFragmentManager)
    }

    fun editPhone() {
        MyApplication.navigateThing["ModifyPhone"] = R.id.action_ModifyPhone_to_MyInfo.toString()
        MyApplication.goto(
            R.id.action_MyInfo_to_UpdatePhone,
            findNavController(),
            parentFragmentManager
        )
    }

    @SuppressLint("NewApi")
    fun showDatePickerDialog() {
        DatePickerDialog(
            requireContext(),
            { _, year, month, dayOfMonth ->
                viewModel.setBirthday(year.toString() + "-" + (month + 1).toString() + "-" + dayOfMonth.toString())
                LogUtils.d(viewModel.user.value!!.birthday)
            },
            LocalDate.now().year,
            LocalDate.now().monthValue - 1,
            LocalDate.now().dayOfMonth
        ).show()
    }

    fun clickEditOrSave() {
        when (viewModel.editText.value) {
            "编辑" -> {
                viewModel.setTitle("保存")
                viewModel.setIsOnClick()
            }
            "保存" -> {
                MyApplication.user?.let {
                    if (MyApplication.imageIsModify) {
                        MyApplication.imageUrl?.let {
                            viewModel.saveHeadImage().observe(viewLifecycleOwner) {
                                if (it.success) {
                                    MyApplication.user!!.headPortrait = MyApplication.imageUrl!!
                                    MyApplication.imageIsModify = false
                                } else {
                                    CircleDialog.Builder().setText(it.message)
                                        .setNegative("取消", null)
                                        .show(parentFragmentManager)
                                }
                            }
                        }
                    }
                    if (viewModel.isModify) {
                        LogUtils.d("!=")
                        viewModel.editUserInfo()
                        viewModel.result.observe(viewLifecycleOwner) {
                            it?.let {
                                //ToastUtils.showShort(it.message)
                                when (it.success) {
                                    true -> {
                                        MyApplication.user = viewModel.user.value
                                        viewModel.setTitle("编辑")
                                        viewModel.setIsOnClick()
                                        viewModel.updateIsModify(false)
                                    }
                                    else -> CircleDialog.Builder().setText(it.message)
                                        .setPositive("重试") {
                                            clickEditOrSave()
                                        }.setNegative("取消", null).show(parentFragmentManager)
                                }
                            }
                        }
                    } else {
                        LogUtils.d("==")
                        viewModel.setTitle("编辑")
                        viewModel.setIsOnClick()
                    }
                }
            }
        }
    }

    fun back() {
        if (viewModel.isOnClick.value!!) viewModel.setIsOnClick()
        if (viewModel.editText.value == "保存") viewModel.setTitle("编辑")
        LogUtils.e(MyApplication.user)
        requireActivity().window.statusBarColor = Color.RED
        if (MyApplication.navigateThing["My"] == "MyInfo") {
            MyApplication.apply {
                navigateThing.remove("My")
                goto(R.id.action_MyInfo_to_My, findNavController(), parentFragmentManager)
            }
        } else if (MyApplication.navigateThing["My"] == "Setting") {
            MyApplication.apply {
                navigateThing.remove("My")
                goto(R.id.action_MyInfo_to_Setting, findNavController(), parentFragmentManager)
            }
        }
    }

    fun takePhoto() {
        AndPermission.with(this).runtime()
            .permission(Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE)
            .onGranted {
                LogUtils.d("申请权限成功！")
                chooseImage()
            }.onDenied {
                LogUtils.d("申请权限失败！")
            }.start()
    }

    private fun chooseImage() {
        MyApplication.imagePicker.selectLimit = 1
        val intent = Intent(requireActivity(), ImageGridActivity::class.java)
        startActivityForResult(intent, 1)
    }
}

